/*
 * Copyright 2009 rashaguo <rashaguo@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */
#include <stdlib.h>
#include "httpclient.h"
#include "utils/logger.h"

class DataCache
{
public:

    int length;
    char *pdata;
    // type for the buffer. like: html text bmp
    char type[64];

};

HttpClient::HttpClient()
{
    LOG_DEBUG("Initial");
    m_dataCache = new DataCache();
    LOG_DEBUG("New memory for data cache");
    m_dataCache->length = 0;
    m_dataCache->pdata = 0;
    m_filename = 0;
}

HttpClient::~HttpClient()
{
    if(m_dataCache->pdata != 0)
    {
        LOG_DEBUG("Free memory for pdata");
        free(m_dataCache->pdata);
        m_dataCache->pdata = 0;
    }
    delete m_dataCache;
    if(m_filename != 0)
    {
        LOG_DEBUG("Free memory for filename");
        free(m_filename);
        m_filename = 0;
    }
}

char* HttpClient::get(std::string url)
{
    LOG_DEBUG("GET method with url: %s", url.c_str());
    http_retcode ret = http_parse_url((char*)url.c_str(), &m_filename);
    if(ret < 0) return (char*)0;

   // return http_get((char*)url.c_str(), &(*data)->pdata, &(*data)->length, (*data)->type);
    ret = http_get(m_filename, &(m_dataCache->pdata),
                &(m_dataCache->length), m_dataCache->type);
    //if(ret)
    if(m_dataCache->length >0)
    {
        //LOG_DEBUG("GET method with data: %s", m_dataCache->pdata);
        return m_dataCache->pdata;
    }
    return (char*)0;
}
